#pragma once
#include <iostream>
#include <fcntl.h>
#include <sys/select.h>
#include <unordered_map>
#include <memory>

#include "Log.hpp"
#include "Socket.hpp"

using namespace SocketMoudle;

// fd_set是按照比特位的位图操作，一个字节等于8个比特位
#define NUM sizeof(fd_set) * 8

const int gradefaultfd = -1;

// select是基于tcpserver进行编写

class SelectServer
{

public:
    SelectServer(int port) : _port(port),
                             _listen_socket(std::make_unique<TcpSocket>()),
                             _isruning(false)
    {
    }

    void Init()
    {
        _listen_socket->BuildTcpSocket(_port);

        for (int i = 0; i < NUM; i++)
        {
            _fd_arry[i] = gradefaultfd;
        }

        // 添加listensockfd到数组中

        _fd_arry[0] = _listen_socket->Fd();
    }

    // 服务器运行
    void Loop()
    {
        fd_set rfds; // 读文件描述符集
        _isruning = true;

        while (_isruning)
        {
            FD_ZERO(&rfds);
            _isruning = true;
            while (_isruning)
            {
                // 清空rfds
                FD_ZERO(&rfds);
                struct timeval timeout = {10, 0};
                int maxfd = gradefaultfd;

                // 遍历辅助数组对rfds进行赋值
                for (int i = 0; i < NUM; i++)
                {
                    if (_fd_arry[i] == gradefaultfd)
                    {
                        continue;
                    }

                    FD_SET(_fd_arry[i], &rfds);

                    // 更新最大值

                    if (maxfd < _fd_arry[i])
                    {
                        maxfd = _fd_arry[i];
                    }
                }

                // 利用select负责进行就绪事件的检测

                int n = select(maxfd + 1, &rfds, nullptr, nullptr, &timeout);

                switch (n)
                {
                case 0:
                    std::cout << "time out....." << std::endl;
                    break;
                case -1:
                    perror("select");
                    break;
                default:
                    std::cout << "有事件就绪......, timeout: " << timeout.tv_sec << ": " << timeout.tv_usec << std::endl;
                    // 把已经就绪的套接字派发给后继模块
                    Dispatcher(rfds);
                }
            }

            _isruning = false;
        }
    }

    void Accepter()
    {
        InetAddr cline;
        // 这里不会阻塞，因为select已经告诉我们_listen_sicket准备就绪
        int newfd = _listen_socket->Accepter(&cline);

        if (newfd < 0)
        {
            return;
        }
        else
        {
            std::cout << "获得了一个新的链接： " << newfd << "cline info: " << cline.PrintDebug() << std::endl;
            int pos = -1;
            for (int j = 0; j < NUM; j++)
            {
                if (_fd_arry[j] == gradefaultfd)
                {
                    pos = j;
                    break;
                }
            }

            if (pos == -1)
            {
                LOG(Logevel::ERROR) << "服务器已经满了..........";
                close(newfd);
            }
            else
            {
                _fd_arry[pos] = newfd;
            }
        }
    }

    void Recever(int who)
    {
        char buffer[1024];
        ssize_t n = recv(_fd_arry[who], buffer, sizeof(buffer) - 1, 0); //
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "cline# " << buffer << std::endl;
            // 把读到的信息返回回去

            std::string message = "echo# ";
            message += buffer;

            send(_fd_arry[who], message.c_str(), message.size(), 0);
        }
        else if (n == 0)
        {
            LOG(Logevel::INFO) << "客户端退出: " << _fd_arry[who];
            close(_fd_arry[who]);
            _fd_arry[who] = gradefaultfd;
        }
        else
        {
            LOG(Logevel::ERROR) << "客户端读取出错: " << _fd_arry[who];
            close(_fd_arry[who]);
            _fd_arry[who] = gradefaultfd;
        }
    }

    void Dispatcher(fd_set &rfds)
    {
        for (int i = 0; i < NUM; i++)
        {
            if (_fd_arry[i] == _listen_socket->Fd())
            {
                if (FD_ISSET(_fd_arry[i], &rfds))
                {
                    Accepter();
                }
            }
            else
            {
                if (FD_ISSET(_fd_arry[i], &rfds))
                {
                    Recever(i);
                }
            }
        }
    }

    ~SelectServer() {}

private:
    uint16_t _port;

    // 指向监听的套接字
    std::unique_ptr<Socket> _listen_socket;

    bool _isruning;
    int _fd_arry[NUM]; // 辅助数组
};
